<?php

namespace api\services\mall;

use api\extensions\ApiBaseService;
use common\models\mall\special\MallSpecialFloorGoodsModel;
use common\models\mall\special\MallSpecialModel;
use common\models\mall\special\MallSpecialFloorModel;
use api\services\goods\GoodsService;

/**
 * 专题
 */
class MallSpecialService extends ApiBaseService
{

    /**
     * 获取专题信息
     * * */
    public static function getSpecial($code)
    {
        try {
            //默认首页——code为空，默认查询首页专题
            if (empty($code)) {
                $special = MallSpecialModel::getDataOne(['is_home' => MallSpecialModel::IS_HOME_YES, 'state' => MallSpecialModel::STATE_ENABLE]);
            } else {
                $special = MallSpecialModel::getDataOne(['code' => $code, 'state' => MallSpecialModel::STATE_ENABLE]);
            }
            if (empty($special)) {
                throw new \Exception('专题已失效');
            }
            // $mkey = 'SPECIAL_CODE_'.$code;
            // $data = CommonCache::getCache($mkey);
            // if($data && empty($refresh)){
            //     return self::jsonSuccess($data);
            // }
            $special['banner'] =  $special['banner'] ? json_decode($special['banner'], true) : [];
            $special['floor'] = self::getSpecialFloor($special['id']);
            return self::jsonSuccess($special);
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }

    /**
     * 获取专题楼层信息
     * $id: 专题ID
     * * */
    public static function getSpecialFloor($id)
    {
        $special_floor = MallSpecialFloorModel::getAll(['special' => $id]);
        if (empty($special_floor)) {
            return [];
        }
       
        foreach ($special_floor as &$value) {
            $value['goods'] = self::getSpecialFloorGoods($value['id'], 1)['data'];
        }
        return $special_floor;
    }

    /**
     * 获取专题楼层商品
     * * */
    public static function getSpecialFloorGoods($special_floor_id, $page = 2)
    {
        try {
            if (empty($special_floor_id)) {
                throw new \Exception('参数异常');
            }
            $special_floor_goods = MallSpecialFloorGoodsModel::getDataAll(['special_floor' => $special_floor_id], $page);
            
            if (empty($special_floor_goods['list'])) {
                throw new \Exception('商品异常');
            }
            //获取商品信息
            $goods = GoodsService::getGoodsInfo(array_column($special_floor_goods['list'], 'gid'), 1, 1);
            return self::jsonSuccess($goods);
        } catch (\Exception $exc) {
            return self::jsonSuccess([]);
        }
    }
}
